<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Api\Service\Purchase\Controllers;


use Framework\BaseClass\Api\Controller;

class IndexController extends Controller
{

    //采购单详情
    public function getPurchaseDetail()
    {
        $purchaseId = request('purchase_id');
        $purchaseRow = \App\Eloquent\Ygt\Purchase::where(['id'=>$purchaseId])->first();
        $purchaseMaterialList = \App\Eloquent\Ygt\PurchaseMaterial::where(['purchase_id' => $purchaseId])->get()->toArray();

        //获取供应商信息
        $supplierName = config('default-value.purchase_list_default_supplier_name');
        $tmpObj = \App\Eloquent\Ygt\SellerCompany::where(['id'=>$purchaseRow['supplier_id']])->first();
        if($tmpObj){
            $supplierName = $tmpObj->title;
        }

        $workflow['supplier_name'] = $supplierName;
        $workflow['finished_date'] = $purchaseRow['finished_date'];
        $workflow['payment_method'] = $purchaseRow['payment_method'];


        $materialList = [];
        $allSumMoney = '';//所有材料总价
        foreach ($purchaseMaterialList as $purchaseMaterialRow) {
            //获取材料名称
            $materialRow = \App\Engine\Product::getProductInfo($purchaseMaterialRow['material_id']);

            //追加材料图片地址
            if ($materialRow['img_id']) {
                $materialRow['img_url'] = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($materialRow['img_id']);
            }

            //追加供应商 归属人
            $materialRow['customer_name'] = '';
            if($materialRow['customer_id']){
                $materialRow['customer_name'] = \App\Eloquent\Ygt\Customer::getOneValueById($materialRow['customer_id'],'customer_name');
            }

            $materialRow['supplier_name'] = '';
            if($materialRow['seller_company_id']){
                $materialRow['supplier_name'] = \App\Eloquent\Ygt\SellerCompany::getOneValueById($materialRow['seller_company_id'],'title');
            }


            //追加材料自定义属性
            $ProductFieldsModel = new \App\Eloquent\Ygt\ProductFields();
            $where = ['product_id' => $materialRow['id']];
            $productFields = $ProductFieldsModel->getData($where);

            $productFields = $productFields->map(function ($item) {
                $data['field_name'] = $item->field_name;
                $comumnName = \App\Engine\Product::getFieldColumn($item->field_type);

                $data['field_value'] = $item->$comumnName.$item['unit'];
                return $data;
            });
            $fieldsList         = $productFields;
            $firstText = $secondText = $thirdText ='';
            if(!empty($fieldsList))
            {
                if(isset($fieldsList[0]))
                {
                    $firstText   = $fieldsList[0]['field_name'].': '.$fieldsList[0]['field_value'];
                }
                if(isset($fieldsList[1]))
                {
                    $secondText  = $fieldsList[1]['field_name'].': '.$fieldsList[1]['field_value'];
                }
                if(isset($fieldsList[2]))
                {
                    $thirdText   = $fieldsList[2]['field_name'].': '.$fieldsList[2]['field_value'];
                }
            }
            $customFieldsText                       = $firstText.' '.$secondText.' '.$thirdText;

            $materialRow['first_text']           = $firstText;
            $materialRow['second_text']          = $secondText;
            $materialRow['third_text']           = $thirdText;
            $materialRow['custom_fields_text']   = $customFieldsText;

            $materialRow['custom_fields'] = $productFields;

            $showMaterialRow = [
                'product_name' => $materialRow['product_name'],
                'img_url' => $materialRow['img_url'],
                'custom_fields' => $materialRow['custom_fields'],
                'price' =>  '¥'.$purchaseMaterialRow['price'],
                'num' => '×'.$purchaseMaterialRow['num']."({$materialRow['unit']})",
                'money' => $purchaseMaterialRow['price']*$purchaseMaterialRow['num'],//总价
            ];

            $showMaterialRow = array_merge($materialRow->toArray(),$showMaterialRow);

            $allSumMoney += $showMaterialRow['money'];

            $materialList[] = $showMaterialRow;
        }

        $content = [
            'material_list' => $materialList,//采购材料名称（所有）
            'all_sum_money' => $allSumMoney,//所有材料总价
        ];

        return $content;
    }

    //删除待采购记录
    public function deleteWaitPurchaseLog(){
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = $userInfo['company_id'];
        $id = request('id');

        \App\Eloquent\Ygt\WaitPurchase::where(['company_id'=>$companyId,'id'=>$id])->delete();
        $result         = ['message'=>'删除成功'];
        return $result;
    }

    //待采购列表
    public function getWaitPurchaseList()
    {
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $companyId = request('company_id');
        if(!$companyId){
            $companyId = $userInfo['company_id'];
        }


        $page   = request('page',1);
        $limit  = request('limit',10);
        $offset = ($page - 1) * $limit;
        $keyword    = request('keyword');

        $count = \App\Eloquent\Ygt\WaitPurchase::where(['company_id'=>$companyId,'status'=>1])->count();
        $waitPurchaseList = \App\Eloquent\Ygt\WaitPurchase::where(['company_id'=>$companyId,'status'=>1])->skip($offset)->take($limit)->orderBy('id','desc')->get();

        $waitPurchaseDealList = [];
        foreach ($waitPurchaseList as $key => $waitPurchaseRow){
            ////处理信息
            $tmpWaitPurchaseId =  $waitPurchaseRow['id'];
            $tmpOrderId = $waitPurchaseRow['order_id'];
            $tmpOrderRow = \App\Eloquent\Ygt\Order::where(['id'=>$tmpOrderId])->first();

            //工单号
            $orderTitle = \App\Engine\Common::changeSnCode($tmpOrderRow['order_title']);
            //材料ID&材料示例图
            $tmpWaitPurchaseMaterialList = \App\Eloquent\Ygt\WaitPurchaseMaterial::where(['wait_purchase_id' => $tmpWaitPurchaseId])->get();
            $materialNameStr = '';$materialImgUrl = '';
            foreach ($tmpWaitPurchaseMaterialList as $tmpWaitPurchaseMaterialRow){
                $tmpMaterialId = $tmpWaitPurchaseMaterialRow['material_id'];
                if(strstr($tmpMaterialId,'A')){
                    $tmpAssemblageMaterialId = str_replace('A','',$tmpMaterialId);
                    $tmpMaterialRow = \App\Eloquent\Ygt\AssemblageMaterial::where(['id'=>$tmpAssemblageMaterialId])->first();
                    if(!empty($tmpMaterialRow)){
                        $tmpMaterialRow['is_assemblage'] = 1;
                    }else{
                        continue;
                    }
                    $materialNameStr.= $tmpMaterialRow['product_name'].",";
                    if(!$materialImgUrl){
                        $imgId = $tmpMaterialRow['img_id'];
                        if ($imgId) {
                            $exampleImg = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($imgId);
                            $item['img_url'] = $exampleImg;
                            $materialImgUrl = $exampleImg;
                        }
                    }
                }else{
                    $tmpMaterialRow = \App\Eloquent\Ygt\Product::where(['id'=>$tmpMaterialId])->first();
                    if(!empty($tmpMaterialRow)){
                        $tmpMaterialRow['is_assemblage'] = 0;
                    }else{
                        //兼容软删除
                        $tmpMaterialRow = \App\Eloquent\Ygt\Product::withTrashed()->where(['id'=>$tmpMaterialId])->first();

                        if(!empty($tmpMaterialRow)) {
                            $tmpMaterialRow['product_name'] = $tmpMaterialRow['product_name']."【已删除】";
                            $tmpMaterialRow['is_assemblage'] = 0;
                        }else{
                            continue;
                        }
                    }
                    $materialNameStr.= $tmpMaterialRow['product_name'].",";
                    if(!$materialImgUrl){
                        $imgId = $tmpMaterialRow['img_id'];
                        if ($imgId) {
                            $exampleImg = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($imgId, false);
                            $item['img_url'] = $exampleImg;
                            $materialImgUrl = $exampleImg;
                        }
                    }
                }
            }

            $waitPurchaseDealList[] = [
                'wait_purchase_id' => $tmpWaitPurchaseId,
                'order_title' => $orderTitle,
                'material_img_url' => $materialImgUrl,
                'material_name_str' => $materialNameStr,
            ];
        }

        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($waitPurchaseDealList, $pagingData);

    }
}